package com.redis.transaction;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA
 * Description:
 *
 * @author liuziyang
 * @date 2020/10/7 12:29
 */
public class TransactionDemo {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("172.20.242.242", 6379);
        String userId = "adc";
        String key = keyFor(userId);
        // setnx做初始化
        jedis.setnx(key, String.valueOf(5));
        System.out.println(doubleAccount(jedis, userId));
        jedis.close();
    }

    public static int doubleAccount(Jedis jedis, String userId) {
        String key = keyFor(userId);
        while (true) {
            jedis.watch(key);
            int value = Integer.parseInt(jedis.get(key));
            value *= 2;
            Transaction tx = jedis.multi();
            tx.set(key, String.valueOf(value));
            List<Object> res = tx.exec();
            // 成功了
            if (Objects.nonNull(res)) {
                break;
            }
        }

        return Integer.parseInt(jedis.get(key));
    }

    public static String keyFor(String userId) {
        return String.format("account_%s", userId);
    }
}
